<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center">
				<div class="flex-start-center-wrap">
					<el-tag effect="plain" size="default" type="primary" class="item-gap">
						<span class="collect-current-time el-icon-time"></span>
						<span class="collect-current-time">{{ currentTime }}</span>
					</el-tag>
					<!--<jk-button class="margin-5-0" :loading="exportLoading" @click="onReportBtn">导出</jk-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :clearable="false" :option-list="workshopList" placeholder="区域" class="search-bar-item-size1 margin-5-0 item-gap" @change="onWorkshopChange"></jk-select>
					<!--<jk-date-picker v-model="searchParams.belongDate" type="date" placeholder="日期" :clearable="false" size="small" class="search-bar-item-size2 margin-5-0 item-gap" @on-enter="onDateChange" />-->
					<!--<el-select v-model="searchParams.scheduleShiftId" :disabled="!searchParams.belongDate" size="small" clearable placeholder="班次" class="search-bar-item-size3 margin-5-0 item-gap" @change="onScheduleShiftChange">
						<el-option
							v-for="item in scheduleShiftList"
							:key="item.id"
							:label="`${item.shiftName} (${item.beginTime} ~ ${item.endTime})`"
							:value="item.id"
						></el-option>
					</el-select>-->
					<!--<jk-select v-model="searchParams.scheduleGroupId" :option-list="scheduleGroupList" value-key-name="id" label-key-name="groupName" placeholder="班组" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable />-->
					<jk-search-input v-model="searchParams.machineCode" placeholder="设备编号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table :row-style="rowClassName" :span-method="machineMergeColMethod" border :stripe="false" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<span v-if="item.keyName === 'code'">{{ scope.row.code }}</span>
						<span v-else-if="item.keyName === 'customerName'" style="font-size: 13px">{{ scope.row.customerName }}</span>
						<span v-else-if="item.keyName === 'machineNum'">{{ scope.row.productOrderMachineList ? scope.row.productOrderMachineList.length : 0 }}</span>
						<div v-else-if="item.keyName === 'progress'" class="flex-center">
							<el-progress type="circle" :percentage="scope.row.orderQty ? parseInt(((scope.row.completionQty || 0) / scope.row.orderQty) * 100) : 0" :width="42"></el-progress>
						</div>
						<div v-else-if="item.keyName === 'coarseSandList'">
							{{ scope.row.coarseSandList ? scope.row.coarseSandList.filter(x => x.typeName === '粗纱').map(x => x.productName).join(',') : '' }}
						</div>
						<div v-else-if="item.keyName === 'paperTubeList'">
							{{ scope.row.paperTubeList ? scope.row.paperTubeList.map(x => x.name).join(',') : '' }}
						</div>
						<div v-else-if="item.keyName === 'unCompletionQty'">
							{{ (scope.row.orderQty || 0) - (scope.row.completionQty || 0) }}
						</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="searchParams.count"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar, formatDate, formatTime } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { orderPriorityList, orderStateList } from '../../../utils/jk/status-option-list';
    import permissionMixin from '../../../mixins/permission-mixin';
    import {
        reportProductionOrderMachineGroupYieldRealTimeMonitoring
    } from '../../../api/production/productionMonitor';
    import { workforcemanagementScheduleList } from '../../../api/schedule/scheduling';
    import { productionPrdReportGetDate } from '../../../api/production/xsReport';
    import mergeMixin from './merge-mixin';

    export default {
        name: 'XsDailyGroupYield',
        components: {
        },
        mixins: [calHeight, getMenuColumn, handlerCache, permissionMixin, mergeMixin],
        data() {
            return {
                prefix: 'production:prdOrder',
                apiItem: {
                    'page': reportProductionOrderMachineGroupYieldRealTimeMonitoring
                },
                timer: {},
                currentTime: '',
                orderStateList: orderStateList,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                workshopList: [],
                scheduleShiftList: [],
                scheduleGroupList: [],
                searchParams: {
                    count: 0,
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    scheduleGroupId: null,
                    belongDate: '',
                    workshopId: null,
                    machineCode: '',
                    scheduleShiftId: null
                },
                moreSearchParams: {
                },
                lineObj: {},
                selectItem: {},
                priorityList: orderPriorityList,
                colors: ['#19be6b', '#2d8cf0']
            };
        },
        methods: {
            rowClassName({ row }) {
                return {
                    backgroundColor: this.lineObj[row.productionLineId].bgColor,
                    color: '#fff'
                };
            },
            onWorkshopChange() {
                this.tableData = [];
                this.$set(this.searchParams, 'scheduleShiftId', null);
                this.$set(this.searchParams, 'scheduleGroupId', null);
                this.$set(this.searchParams, 'shiftId', null);
                this.$set(this.searchParams, 'shiftName', null);
                this.scheduleShiftList = [];
                this.getDateScheduleShiftOptionRequest();
            },
            onDateChange() {
                this.$set(this.searchParams, 'scheduleShiftId', null);
                this.$set(this.searchParams, 'scheduleGroupId', null);
                this.$set(this.searchParams, 'shiftName', null);
                this.$set(this.searchParams, 'shiftId', null);
                this.tableData = [];
                this.scheduleShiftList = [];
                this.getDateScheduleShiftOptionRequest();
            },
            getDateScheduleShiftOptionRequest() {
                if (this.searchParams.workshopId && this.searchParams.belongDate) {
                    return workforcemanagementScheduleList({
                        belongDate: [this.searchParams.belongDate, this.searchParams.belongDate],
                        workshopId: this.searchParams.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData && resData.length) {
                                this.scheduleShiftList = resData[0].scheduleShiftList;
                            }
                        }
                    });
                }
            },
            onScheduleShiftChange(e) {
                let item = {};
                if (e) {
                    item = this.scheduleShiftList.find(x => x.id === e);
                } else {
                    item = {
                        id: null,
                        shiftId: null,
                        shiftName: null,
                        scheduleId: null
                    };
                }
                this.$set(this.searchParams, 'scheduleGroupId', null);
                this.scheduleGroupList = item.scheduleGroupList;
                this.$set(this.searchParams, 'scheduleId', item.scheduleId);
                this.$set(this.searchParams, 'scheduleShiftId', item.id);
                this.$set(this.searchParams, 'shiftId', item.shiftId);
                this.$set(this.searchParams, 'shiftName', item.shiftName);
                this.getOpenMachineListRequest();
            },
            getOpenMachineListRequest() {
                if (this.searchParams.workshopId && this.searchParams.processId && this.searchParams.belongDate && this.searchParams.scheduleShiftId) {
                    this.tableLoading = true;
                    productionPrdReportGetDate({
                        workshopId: this.searchParams.workshopId,
                        processId: this.searchParams.processId,
                        scheduleShiftId: this.searchParams.scheduleShiftId,
                        belongDate: this.searchParams.belongDate
                    }).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.$set(this.searchParams, 'prdReportMachineList', res.data.res);
                            this.calTotal();
                        }
                    });
                }
            },
            clearRadioRowEvent() {
                this.selectItem = {};
                this.$refs.orderTable.$refs.xTable.clearRadioRow();
            },
            onResetSearchBtn() {
                Object.assign(this.$data.moreSearchParams, this.$options.data().moreSearchParams);
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onFinish() {
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                this.currentTime = formatTime(Date.now());
                // this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                await this.getMenuColumnListRequest();
                await this.getDateScheduleShiftOptionRequest();
                await this.getListRequest();
                this.runData();
                this.tableLoading = false;
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.pageNo = null;
                params.pageSize = null;
                this.$confirm('是否确认导出所有数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem.page(params);
                }).then(res => {
                    this.exportLoading = false;
                    if (res.data.status === 200) {
                        import('@/vendor/Export2Excel').then(excel => {
                            const tHeader = this.tableColumnList.map(x => x.title);
                            const filterVal = this.tableColumnList.map(x => x.keyName);
                            const list = JSON.parse(JSON.stringify(res.data.res.itemList)).map(item => {
                                return item;
                            });
                            const data = this.formatJson(filterVal, list);
                            excel.export_json_to_excel({
                                header: tHeader,
                                data,
                                filename: `${res.data.res.workshopName}-${res.data.res.shiftName}-${res.data.res.groupName}-${this.searchParams.belongDate}`,
                                autoWidth: true,
                                bookType: 'xlsx'
                            });
                        });
                    }
                }).catch(() => {});
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            },
            /** 查询列表 */
            getListRequest() {
                if (this.searchParams.workshopId) {
                    this.tableLoading = true;
                    this.selectItem = {};
                    const params = { ...this.moreSearchParams, ...this.searchParams };
                    return this.apiItem['page'](params).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.lineObj = {};
                            this.tableData = res.data.res ? res.data.res.map(x => {
                                if (!this.lineObj[x.productionLineId]) {
                                    idx = 0;
                                    this.lineObj[x.productionLineId] = {
                                        bgColor: this.colors[idx],
                                        productionLineName: x.productionLineName
                                    };
                                }
                                return x;
                            }) : [];
                            let idx = 0;
                            for (const item in this.lineObj) {
                                if (idx >= 2) idx = 0;
                                idx++;
                                this.lineObj[item].bgColor = this.colors[idx - 1];
                            }
                            this.searchParams.count = res.data.count;
                        }
                    });
                } else {
                    tipsBar(this, 'custom', 'warning', '区域不能为空!');
                }
            },
            runData() {
                clearInterval(this.timer);
                let count = 0;
                this.timer = setInterval(() => {
                    this.currentTime = formatTime(Date.now());
                    count++;
                    if (count >= 5) {
                        this.getListRequest();
                        count = 0;
                    }
                }, 5000);
            }
        },
        mounted() {
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            this.$set(this.searchParams, 'workshopId', this.workshopList.find(x => x.name === '前纺区域') ? this.workshopList.find(x => x.name === '前纺区域').id : this.$store.state.user.userWorkshop.defaultWorkshopId);
        },
        beforeRouteEnter(to, from, next) {
            next((_this) => {
                _this.getDependentData();
            });
        },
        beforeRouteLeave(to, from, next) {
            clearInterval(this.timer);
            next();
        }
    };
</script>

<style scoped>
    .collect-current-time {
        margin-right: 4px;
        font-size: 16px;
    }
</style>
